#!/usr/bin/python

import xbmc
import xbmcgui
import xbmcplugin
import iplayer2 as iplayer
import os, os.path
import urllib
import sys

# action codes
ACTION_MOVE_LEFT        = 1    
ACTION_MOVE_RIGHT       = 2
ACTION_MOVE_UP          = 3
ACTION_MOVE_DOWN        = 4
ACTION_PAGE_UP          = 5
ACTION_PAGE_DOWN        = 6
ACTION_SELECT_ITEM      = 7
ACTION_HIGHLIGHT_ITEM   = 8
ACTION_PARENT_DIR       = 9
ACTION_PREVIOUS_MENU    = 10 # INFO
ACTION_SHOW_INFO        = 11 # MENU
ACTION_PAUSE            = 12
ACTION_STOP             = 13
ACTION_NEXT_ITEM        = 14
ACTION_PREV_ITEM        = 15
ACTION_PLAY             = 79

ACTION_META_BACK = (ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, ACTION_SHOW_INFO)

XML_PROGRAMMES = [
    (9500, 'synopsis'),
    (9501, 'synopsis_thumb'),
    (9502, 'synopsis_thumb_shadow'),
    (9503, 'synopsis_title'),
    (9505, 'synopsis_summary'),
    (9510, 'list'),
    (9515, 'list_title'),
    (9520, 'progress'),
    (9521, 'progress_text'),
    (9522, 'progress_icon'),
    (9531, 'programmes_title'),
    (9750, 'buttons'),
    (9751, 'button_channel'),
    (9752, 'button_subcat'),
    (9753, 'button_search'),
    (9754, 'button_options'),    
]
XML_CHANNELS_DIALOG = [
    (9801, 'channels'),
    (9802, 'categories'),
]

DIR_ROOT = os.getcwd()
DIR_CACHE = os.path.join(DIR_ROOT, 'cache')
DIR_THUMBS = os.path.join(DIR_CACHE, 'thumbs')

def log(s):
    print s

def get_thumbnail(programme, size='big'):
    pid = programme.pid
    thumbfilename = "%s.%s.jpg" % (pid, size)
    fn = os.path.join(DIR_THUMBS, thumbfilename)
    if not os.path.exists(fn):
        url = programme.get_thumbnail(size)
        urllib.urlretrieve(url, fn)
    return fn


class ChannelsDialog(xbmcgui.WindowXMLDialog):
    def __new__(self, *args, **kwargs):
        return super(ChannelsDialog, self).__new__(
            ChannelsDialog, "script-iplayer-channels-dialog.xml", DIR_ROOT, "Default")
    
    def __init__(self):
        xbmcgui.lock()
        self.controls = {}
        self.channel = None

    def onInit(self):
        xbmcgui.unlock()
        for (cid, name) in XML_CHANNELS_DIALOG:
            try:
                self.controls[name] = self.getControl(cid)
            except:
                print "Control %s (%d) doesn't exist" % (name, cid)
                xbmcgui.unlock()
                raise
        xbmcgui.unlock()
        self.populateChannels()

    def onAction(self, action):
        if action in ACTION_META_BACK:
            self.close()
            
    def populateChannels(self):
        self.channels = [
            #('Popular', 'popular'), ('Featured', 'featured'),
            ('BBC One', 'bbc_one'), ('BBC Two', 'bbc_two'), 
            ('BBC Three', 'bbc_three'), ('BBC Four', 'bbc_four'),
            ('CBBC', 'cbbc'), ('CBeebies', 'cbeebies'), 
            ('BBC News Channel', 'bbc_news24'), ('BBC Parliament', 'bbc_parliament'),  
        ]
        self.channelmap = {}
        xbmcgui.lock()
        i = iplayer.iplayer()
        for name, alias in self.channels:
            channel = i.get_channel(alias)
            thumbnail = "%s.jpg" % alias
            item = xbmcgui.ListItem(label=name, thumbnailImage=thumbnail)
            self.controls['channels'].addItem(item)
            self.channelmap[item] = channel
        xbmcgui.unlock()

        for name, title in iplayer.categories_list: 
            item = xbmcgui.ListItem(label=title)
            self.controls['categories'].addItem(item)

    def onFocus(self, controlId):
        pass

    def onClick(self, controlId):
        if controlId == 9801:
            item = self.controls['channels'].getSelectedItem()
            channel = self.channelmap[item]
            self.channel = channel
            self.close()
    
    def get_channel(self):
        return self.channel
        

class Programmes(xbmcgui.WindowXML):
    def __new__(self, *args, **kwargs):
        return super(Programmes, self).__new__(Programmes, "script-iplayer-programmes.xml", DIR_ROOT, "Default")
    
    def __init__(self, channel):
        xbmcgui.lock()
        self.controls = {}
        self.progmap = {}
        self.channel = channel
    
    def onInit(self):
        for (cid, name) in XML_PROGRAMMES:
            try:
                self.controls[name] = self.getControl(cid)
            except:
                print "Control %s (%d) doesn't exist'" % (name, cid)
        xbmcgui.unlock()
        self.populate(self.channel)
    
    def populate(self, channel):    
        self.channel = channel
        self.progmap = {}
        xbmcgui.lock()
        self.controls['list'].setVisible(False)
        self.controls['list'].reset()
        self.controls['progress'].setVisible(True)
        self.controls['programmes_title'].setLabel(channel.name)
        self.controls['progress_text'].setLabel("Populating list...")
        self.controls['list_title'].setLabel("Popular")
        xbmcgui.unlock()
        programmes = channel.popular
        unsorted = []
        for i, p in enumerate(programmes):
            progress = "Fetching programmes...[CR]%d of %d" % (i+1, len(programmes))
            self.controls['progress_text'].setLabel(progress)
            try:
                thumbfn = get_thumbnail(p, 'small')
                title = p.title or ''
                summary = p.summary or ''
                li = xbmcgui.ListItem(
                    label=title,
                    label2=summary,
                    thumbnailImage=thumbfn)
                unsorted.append(li)
                self.progmap[li] = p
            except:
                raise
        xbmcgui.lock()
        for li in sorted(unsorted, key=lambda x: x.getLabel()):
            self.controls['list'].addItem(li)
        self.controls['progress'].setVisible(False)
        self.controls['list'].setVisible(True)
        xbmcgui.unlock()
        self.update_synopsis()
    
    def onAction(self, action):
        if action in ACTION_META_BACK:
            print "bye"
            self.close()
        else:
            self.update_synopsis()
                
    def onClick(self, controlId):
        if controlId == 9751:
            cd = ChannelsDialog()
            cd.doModal()
            if cd.get_channel():
                self.populate(cd.get_channel())
    
    def onFocus(self, controlId):
        pass
    
    def update_synopsis(self):
        li = self.controls['list'].getSelectedItem()
        p = self.progmap[li]
        if p:
            self.set_synopsis(p)
    
    def set_synopsis(self, programme):
        xbmcgui.lock()
        thumbfn = get_thumbnail(programme)
        self.controls['synopsis_title'].setLabel(programme.title or '(Unknown Programme)')
        self.controls['synopsis_summary'].setLabel(programme.summary or '')
        self.controls['synopsis_thumb'].setImage(thumbfn)
        self.controls['synopsis_thumb_shadow'].setImage(thumbfn)
        xbmcgui.unlock()

if __name__ == "__main__":
    ip = iplayer.iplayer()
    w = Programmes(ip.bbc_one)
    w.doModal()
    #cd = ChannelsDialog()
    #cd.doModal()
    del w


